/*
 * Copyright 2014-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
<template>
  <div>

    <div class="module-wrapper">
      <div class="search-part">
        <div v-if="!disabled" class="search-part-left">
          <el-button type="primary" class="search-part-left-btn" @click="$store.dispatch('switch_creat_user_dialog')">{{ this.$t('privateKey.addUser') }}</el-button>
          <el-button type="primary" class="search-part-left-btn" @click="$store.dispatch('switch_import_private_key_dialog')">{{ this.$t('privateKey.importPrivateKey') }}</el-button>
          <el-tooltip effect="dark" :content="$t('privateKey.addUserTips')" placement="top-start">
            <i class="el-icon-info" />
          </el-tooltip>
        </div>
        <div class="search-part-right">
          <el-input v-model="userName" :placeholder="$t('privateKey.searchUser')" class="input-with-select" clearable style="width: 370px;">
            <el-button slot="append" icon="el-icon-search" @click="search" />
          </el-input>
        </div>
      </div>
      <div class="search-table">
        <el-table v-loading="loading" :data="privateKeyList" tooltip-effect="dark">
          <el-table-column v-for="head in privateKeyHead" :key="head.enName" :label="head.name" show-overflow-tooltip :width="tdWidth[head.enName] || ''" align="center">
            <template slot-scope="scope">
              <template v-if="head.enName!='operate'">
                <span v-if="head.enName ==='userStatus'" :style="{'color': statusColor(scope.row[head.enName])}">{{ userStatus(scope.row[head.enName]) }}</span>
                <span v-else-if="head.enName ==='address'">
                  <i v-show="scope.row[head.enName]" class="wbs-icon-copy font-12 copy-public-key" :title="$t('privateKey.copy')" @click="copyPubilcKey(scope.row[head.enName])" />
                  {{ scope.row[head.enName] }}
                </span>
                <span v-else-if="head.enName ==='signUserId'">
                  <i v-show="scope.row[head.enName]" class="wbs-icon-copy font-12 copy-public-key" :title="$t('privateKey.copy')" @click="copyPubilcKey(scope.row[head.enName])" />
                  {{ scope.row[head.enName] }}
                </span>
                <span v-else-if="head.enName ==='userId'">
                  <el-tooltip :content="scope.row['hasPk'] == 1 ? $t('privateKey.privateKey'):$t('privateKey.publicKey')" placement="top" effect="dark">
                    <i class="wbs-icon-key-b font-12" :style="{'color': scope.row['hasPk'] == 1 ? '#FFC31F':'#4F9DFF'}" />
                  </el-tooltip>
                  {{ scope.row[head.enName] }}
                </span>
                <span v-else>{{ scope.row[head.enName] }}</span>
              </template>
              <template v-else>
                <el-button v-if="scope.row['hasPk'] ==1" :disabled="disabled" type="text" size="small" :class="{'grayColor': disabled}" @click="exportFile(scope.row)">{{ $t('system.export') }}</el-button>
                <el-button v-else :disabled="disabled" type="text" size="small" :class="{'grayColor': disabled}" @click="bindPrivateKey(scope.row)">{{ $t('text.addContractAddress') }}</el-button>
                <el-button :disabled="disabled" type="text" size="small" :class="{'grayColor': disabled}" @click="modifyDescription(scope.row)">{{ $t('text.update') }}</el-button>
                <!-- <el-button v-else :disabled="disabled" type="text" size="small" :class="{'grayColor': disabled}" @click="freezeThaw(scope.row)">{{freezeOrThawBtn(1)}}</el-button> -->
              </template>
            </template>

          </el-table-column>

        </el-table>
        <el-pagination class="page" :current-page="currentPage" :page-sizes="[10, 20, 30, 50]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>
    <el-dialog v-if="$store.state.creatUserVisible" :visible.sync="$store.state.creatUserVisible" :title="$t('privateKey.createUser')" width="640px" :append-to-body="true" class="dialog-wrapper" center>
      <v-creatUser ref="creatUser" @creatUserClose="creatUserClose" @bindUserClose="bindUserClose" />
    </el-dialog>
    <el-dialog v-if="$store.state.importPrivateKey" :visible.sync="$store.state.importPrivateKey" :title="$t('privateKey.importPrivateKey')" width="640px" :append-to-body="true" class="dialog-wrapper" center>
      <v-importKey ref="importKey" @importPrivateKeySuccess="importPrivateKeySuccess" />
    </el-dialog>
    <el-dialog v-if="$store.state.exportRivateKey" :visible.sync="$store.state.exportRivateKey" :title="$t('system.export')" width="640px" :append-to-body="true" class="dialog-wrapper" center>
      <export-key :export-info="exportInfo" />
    </el-dialog>
    <el-dialog v-if="$store.state.bindKey" :visible.sync="$store.state.bindKey" :title="$t('privateKey.bindPrivateKey')" width="640px" :append-to-body="true" class="dialog-wrapper" center>
      <bind-key :bind-info="bindInfo" @importPrivateKeySuccess="importPrivateKeySuccess" />
    </el-dialog>
  </div>
</template>

<script>
import contentHead from '@/components/contentHead'
import creatUser from './components/creatUser.vue'
import importKey from './components/importKey.vue'
import ExportKey from './components/exportKey.vue'
import BindKey from './components/bindKey.vue'
import { getUserList, getUserDescription, bindPrivateKeyInterface } from '@/api/exercises'
const Base64 = require('js-base64').Base64
import errcode from '@/utils/errcode'
export default {
  name: 'PrivateKeyManagement',
  components: {
    'v-contentHead': contentHead,
    'v-creatUser': creatUser,
    'v-importKey': importKey,
    ExportKey,
    BindKey
  },
  data() {
    return {
      userName: this.$route.query.userName || '',
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      privateKeyList: [],
      tdWidth: {
        publicKey: 450
      },
      disabled: false,
      exportInfo: {},
      bindInfo: {}
    }
  },
  computed: {
    privateKeyHead() {
      const data = [
        {
          enName: 'userName',
          name: this.$t('privateKey.userName')
        },
        {
          enName: 'userId',
          name: this.$t('privateKey.userId')
        },
        {
          enName: 'description',
          name: this.$t('privateKey.description')
        },
        {
          enName: 'address',
          name: this.$t('privateKey.userAddress')
        },
        {
          enName: 'signUserId',
          name: this.$t('privateKey.signUserId')
        },
        {
          enName: 'userStatus',
          name: this.$t('privateKey.userStatus')
        },
        {
          enName: 'operate',
          name: this.$t('nodes.operation')
        }
      ]
      return data
    }
  },
  created() {
    if (this.$route.query.userParam) {
      this.userName = this.$route.query.userParam
    }
  },
  mounted() {
    if ((localStorage.getItem('root') === 'admin' || localStorage.getItem('root') === 'developer') && 1) {
      this.disabled = false
    } else {
      this.disabled = true
    }
    if (1 && (localStorage.getItem('configData') == 3 || localStorage.getItem('deployType') == 0)) {
      this.getUserInfoData()
    }
  },
  methods: {
    bindPrivateKey(row) {
      this.bindInfo = row
      this.$store.dispatch('exercises/switch_bind_key_dialog')
    },
    changGroup() {
      this.getUserInfoData()
    },
    getUserInfoData() {
      this.loading = true
      const reqData = {
        groupId: 1,
        pageNumber: this.currentPage,
        pageSize: this.pageSize
      }
      const reqQuery = {
        userParam: this.userName.replace(/^\s+|\s+$/g, '')
      }
      if (localStorage.getItem('root') === 'developer') {
        reqQuery.account = localStorage.getItem('user')
      }
      getUserList(reqData, reqQuery)
        .then(res => {
          this.loading = false
          if (res.code === 0) {
            this.privateKeyList = res.data || []
            this.total = res.data.totalCount
          } else {
            this.$messageOnce({
              message: this.$chooseLang(res.code),
              type: 'error',
              duration: 2000
            })
          }
        })
        .catch(err => {
          this.loading = false
          this.$messageOnce({
            message: err.data || this.$t('text.systemError'),
            type: 'error',
            duration: 2000
          })
        })
    },
    search() {
      this.currentPage = 1
      this.getUserInfoData()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.getUserInfoData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getUserInfoData()
    },
    creatUserInfo() { },
    creatUserClose() {
      this.getUserInfoData()
    },
    bindUserClose() {
      this.getUserInfoData()
    },
    importPrivateKeySuccess() {
      this.getUserInfoData()
    },
    handleClose: function() {
      this.$refs.creatUser.modelClose()
    },
    modifyDescription(params) {
      this.$prompt(this.$t('privateKey.inputDescription'), '', {
        confirmButtonText: this.$t('text.sure'),
        cancelButtonText: this.$t('text.cancel'),
        inputValue: params.description,
        inputPattern: /^.{1,120}$/,
        inputErrorMessage: this.$t('text.textInfo')
      })
        .then(({ value }) => {
          this.userDescriptionInfo(value, params)
        })
        .catch(() => {
          this.$messageOnce({
            type: 'info',
            message: this.$t('text.cancel')
          })
        })
    },
    exportFile(params) {
      this.exportInfo = params
      this.$store.dispatch('exercises/switch_export_rivate_key_dialog')
    },
    // bindPrivateKey(value, params) {
    //         let reqData = {
    //         groupId: params.groupId,
    //         privateKey: Base64.encode(value),
    //         userId: params.userId,

    //     };
    //     bindPrivateKeyInterface(reqData)
    //         .then(res => {
    //             if (res.code === 0) {
    //                 this.getUserInfoData();
    //                 this.$messageOnce({
    //                     type: "success",
    //                     message: this.$t("privateKey.importPrivateKeySuccess")
    //                 });
    //             } else {
    //                 this.$messageOnce({
    //                     message: this.$chooseLang(res.code),
    //                     type: "error",
    //                     duration: 2000
    //                 });
    //             }
    //         })
    //         .catch(err => {
    //             this.$messageOnce({
    //                 message: err.data || this.$t('text.systemError'),
    //                 type: "error",
    //                 duration: 2000
    //             });
    //         });
    // },
    userDescriptionInfo(value, params) {
      const reqData = {
        userId: params.userId,
        description: value
      }
      getUserDescription(reqData)
        .then(res => {
          if (res.code === 0) {
            this.getUserInfoData()
            this.$messageOnce({
              type: 'success',
              message: this.$t('privateKey.updateUserSuccess')
            })
          } else {
            this.$messageOnce({
              message: this.$chooseLang(res.code),
              type: 'error',
              duration: 2000
            })
          }
        })
        .catch(err => {
          this.$messageOnce({
            message: err.data || this.$t('text.systemError'),
            type: 'error',
            duration: 2000
          })
        })
    },
    freezeThaw(params) {
      this.$prompt(this.$t('privateKey.inputimportPrivateKey'), '', {
        confirmButtonText: this.$t('text.sure'),
        cancelButtonText: this.$t('text.cancel'),
        // inputValue: val.description,
        // inputPattern: /([a-fA-F0-9]{1,100})$/,
        // inputErrorMessage: this.$t('privateKey.validatorPrivateKey16')
        inputPlaceholder: this.$t('privateKey.validatorPrivateKey16')
      })
        .then(({ value }) => {
          this.bindPrivateKey(value, params)
        })
        .catch(() => {
          this.$messageOnce({
            type: 'info',
            message: this.$t('text.cancel')
          })
        })
    },
    copyPubilcKey(val) {
      if (!val) {
        this.$messageOnce({
          type: 'fail',
          showClose: true,
          message: this.$t('text.copyErrorMsg'),
          duration: 2000
        })
      } else {
        this.$copyText(val).then(e => {
          this.$messageOnce({
            type: 'success',
            showClose: true,
            message: this.$t('text.copySuccessMsg'),
            duration: 2000
          })
        })
      }
    },
    userStatus(key) {
      let str = ''
      switch (key) {
        case 1:
          str = this.$t('privateKey.normal')
          break
        case 2:
          str = this.$t('privateKey.disable')
          break
        default:
          str = this.$t('privateKey.normal')
          break
      }
      return str
    },
    statusColor(key) {
      let color = ''
      switch (key) {
        case 1:
          color = '#58cb7d'
          break
        case 2:
          color = '#ed5454'
          break
        default:
          color = '#58cb7d'
          break
      }
      return color
    },
    freezeOrThawBtn(val) {
      let str = ''
      switch (val) {
        case 1:
          str = this.$t('privateKey.freeze')
          break
        case 2:
          str = this.$t('privateKey.thaw')
          break
      }
      return str
    }
  }
}
</script>
<style scoped>
@import "./privateKeyManagement.css";
</style>
